import time
import json
import webapp2

from webapp2_extras.i18n import gettext as _

from google.appengine.api import users
from apnetmodels.basicmodels import immeuble, lot_types
from common import functions
from wtforms.ext.appengine.db import model_form

from BaseHandler import BaseHandler

class LotTypes(BaseHandler):
    def __init__(self, *args, **kwargs):
        super(LotTypes, self).__init__(*args, **kwargs)
        self.fields = {
                       'syndic': _('Syndic'), 'name': _('Name'), 'shortname': _('Short name'), 'groupe': _('Group')
                       }
    
    def get(self, imm_id, command, lt_id=None):
        if not command or command == 'list':
            self.op_list(imm_id)
        if command == 'add':
            self.op_add(imm_id)
        if command == 'edit':
            self.op_edit(imm_id, lt_id)
        if command == 'list_json':
            self.op_list_json(imm_id)
        if command == 'predefine':
            self.op_predefine(imm_id)
            
    
    def post(self, imm_id, command=None, lt_id=None):
        if not command or command == 'list':
            self.op_list(imm_id)
        if command == 'add':
            self.op_add(imm_id)
        if command == 'edit':
            self.op_edit(imm_id, lt_id)
        if command == 'predefine':
            self.op_predefine(imm_id)
    
    def op_list(self, imm_id):
        au = functions.GetAPNETUser()
        if not au:
            self.redirect(webapp2.uri_for('registration', command="user"))
            return
        
        imm = immeuble.get_by_id(int(imm_id))
        if not imm:
            self.redirect(webapp2.uri_for('mainpage'))
            return
        
        template_values = {
                           'title': _('Types of lot. %s' % imm.name),
                           'header': _('%s. Types of lot.' % imm.name),
                           'app_user': au,
                           'immeuble': imm,
                           'lurl': users.create_logout_url('/'),
                           'section': 'parametrage',
                           'leftmenu': 'lot_types',
                           'fields': self.fields
                           }

        template = self.jinja2.get_template('templates/lot_types.html')
        self.response.out.write(template.render(template_values))
    
    def op_list_json(self, imm_id):
        au = functions.GetAPNETUser()
        if not au:
            self.redirect(webapp2.uri_for('registration', command="user"))
            return
        
        imm = immeuble.get_by_id(int(imm_id))
        if not imm:
            self.redirect(webapp2.uri_for('mainpage'))
            return
        
        types = lot_types.all().filter("syndic =", imm.syndic).run()
        lt = []
        for t in types:
            lt.append([unicode(t.name), unicode(t.shortname), unicode(t.groupe), str(t.key().id())])
        ret = {}
        ret['aaData'] = lt
        self.response.out.write(json.dumps(ret))
    
    def op_add(self, imm_id):
        au = functions.GetAPNETUser()
        if not au:
            self.redirect(webapp2.uri_for('registration', command="user"))
            return
        ok_message = ''
        
        imm = immeuble.get_by_id(int(imm_id))
        
        LotTypeForm = model_form(lot_types, exclude=['syndic'])
            
        if self.request.method == 'GET':
            form = LotTypeForm()
            
        if self.request.method == 'POST':
            form = LotTypeForm(self.request.POST)
            
            if form.validate():
                new_lot_type = lot_types(name = 'name', shortname = 'shortname', syndic=imm.syndic)
                form.populate_obj(new_lot_type)
                new_lot_type.put()
                while not new_lot_type.is_saved():
                    time.sleep(2)
                
                ok_message = _('Type of lot was added.')
        
        template_values = {'form': form, 'ok_message': ok_message, 'fields': self.fields}
        
        template = self.jinja2.get_template('templates/base_form.html')
        self.response.out.write(template.render(template_values))
    
    def op_edit(self, imm_id, lt_id):
        au = functions.GetAPNETUser()
        if not au:
            self.redirect(webapp2.uri_for('registration', command="user"))
            return
        ok_message = ''
        
        imm = immeuble.get_by_id(int(imm_id))
        if not imm:
            self.redirect(webapp2.uri_for('mainpage'))
            return    
        lot_type = lot_types.get_by_id(int(lt_id))
        if not lot_type: 
            self.redirect(webapp2.uri_for('mainpage'))
            return    
            
        LotTypeForm = model_form(lot_types, exclude=['syndic'])
            
        if self.request.method == 'GET':
            form = LotTypeForm(obj = lot_type)

        if self.request.method == 'POST':
            form = LotTypeForm(self.request.POST)
            
            if form.validate():
                form.populate_obj(lot_type)
                lot_type.put()
                
                ok_message = _('Type of lot was saved.')
        
        template_values = {'form': form, 'ok_message': ok_message, 'fields': self.fields}
        
        template = self.jinja2.get_template('templates/base_form.html')
        self.response.out.write(template.render(template_values))


    def op_predefine(self, imm_id):

        au = functions.GetAPNETUser()
        if not au:
            self.redirect(webapp2.uri_for('registration', command="user"))
            return
        
        imm = immeuble.get_by_id(int(imm_id))
        if not imm:
            self.redirect(webapp2.uri_for('mainpage'))
            return
        
        lot_types_template =  imm.syndic.get_prdefine_template("lot_types") 
        
        if self.request.method == 'POST':
            imm.syndic.set_predefine_lottypes()
            self.redirect(webapp2.uri_for('parametrage_type_de_lot', imm_id=imm_id, command='list'))
            return
        
        template_values = {
            'title': _('Types of lot template'),
            'header': _('Set of default types of lot'),
            'immeuble': imm,
            'table': lot_types_template,
            'app_user': au,
            'lurl': users.create_logout_url('/'),
            'section': 'parametrage',
            'fields': self.fields
        }
        
        template = self.jinja2.get_template('templates/lot_types_predefine.html')
        self.response.out.write(template.render(template_values))

